/*
二不同
*/
cc.Class({
    extends: cc.Component,

    properties: {
        k3ToggleList:{
            default:[],
            type:cc.Toggle
        },
        k3ChangeTg: {
            default:null,
            type:cc.Toggle
        },
        labSelectedAmount:{
            default:null,
            type:cc.Label
        },
        edMutipleNum:{
            default:null,
            type:cc.EditBox
        },
        edIssueNum:{
            default:null,
            type:cc.EditBox
        },

        spYellow:{
            default:null,
            type:cc.SpriteFrame
        },

        spRed:{
            default:null,
            type:cc.SpriteFrame
        },

        labTip:{
            default:null,
            type:cc.Label
        },

        ndBetPanle:{
            default: null,
            type: cc.Node
        },

        //机选清空切换按钮
        tgSelect:{
            default:null,
            type:cc.Toggle
        },

        tgIsStop:{
            default:null,
            type:cc.Toggle
        },

        ndAddAward:{
            default:null,
            type:cc.Node
        },

        BASEMONEY:2,
        _rules:"",//规则
        _lotteryID:0,//彩种id
        _isNorm:1,//1标准0胆拖
        _curMoney:0,
        _curBetNum:0,
        _totalisuse:0,
        _isStops:-1,//追号到截止

        _redDiceNums:[],
        _yellowDiceNums:[],
        _isMiss:false,//是否开启遗漏
        _betManage:null
    },

    initReset:function(){
        if(this._isMiss )
        {
            this._betManage.showK3Miss(this.k3ToggleList,this._lotteryID,this._lotteryID + this._rules.toString(),false);
        }
    },

    //退出界面时重置界面
    clearAllBetRecord:function(){
        this.clearAllBet();
    },

    // use this for initialization
    onLoad: function () {  
          this.node.on(cc.Node.EventType.TOUCH_END, function (event) {
                var contentRect = this.ndBetPanle.getBoundingBoxToWorld();
                var touchLocation = event.getLocation();
                contentRect.x = contentRect.x -20;
                contentRect.width = 1080;
                if(cc.rectContainsPoint(contentRect, touchLocation) == false){//关闭投注界面
                    this.onClose();
                }
        }, this);

        this._totalisuse = 87;//一天期数
        this.initPanel();
        this._betManage = cc.find("Canvas").getChildByName("ChatRoomPage").getChildByName("BetManage").getComponent("BetManage");
    },

    showAddAward:function(data){
        for(var i=0;i<data.length;i++)
        {
            var codestr = data[i].PlayCode.toString();
            var code = codestr.substring(codestr.length-2,codestr.length);
            var index = this._rules.indexOf(code); 
            if(index != -1)
            {
                this.ndAddAward.active = true;
                return;
            }
        }
    },

    initPanel:function(){
        for(var i=0;i<this.k3ToggleList.length;i++) 
        {
            var checkEventHandler = new cc.Component.EventHandler();
            checkEventHandler.target = this.node; 
            checkEventHandler.component = "K3DoubleDiffContent"
            checkEventHandler.handler = "onClickCallBack";
            checkEventHandler.customEventData = {num:i+1,type:0};//0无1红2黄
            this.k3ToggleList[i].getComponent(cc.Toggle).checkEvents.push(checkEventHandler);
        }
    },

    onClickCallBack:function(toggle, customEventData){
        var num =  customEventData["num"];
        var type = toggle.getComponent(cc.Toggle).checkEvents[0].customEventData.type;
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            if(this._isNorm == 0)//胆拖
            { 
                if(this._yellowDiceNums.length >= 1)
                {
                    ComponentsUtils.showTips("胆码最多只能选择1个");
                    toggle.getComponent(cc.Toggle).isChecked = false;
                    return;
                }
                this._yellowDiceNums.push(num);
                toggle.checkMark.spriteFrame = this.spYellow;  
                toggle.getComponent(cc.Toggle).checkEvents[0].customEventData = {num:num,type:2};
                this.updateTgSelect();
                this.checkBet();
                return;
            }
            else if(this._isNorm == 1)
            {
                this._redDiceNums.push(num);
                toggle.checkMark.spriteFrame = this.spRed;
                toggle.getComponent(cc.Toggle).checkEvents[0].customEventData = {num:num,type:1};
                this.updateTgSelect();
                this.checkBet();
                return;
            }
        }
        else
        {
            if(type == 1)
            {
                Utils.removeByValue(this._redDiceNums,num);
                toggle.getComponent(cc.Toggle).checkEvents[0].customEventData = {num:num,type:0};
            }
            else if(type == 2)
            {
                Utils.removeByValue(this._yellowDiceNums,num);
                toggle.getComponent(cc.Toggle).checkEvents[0].customEventData = {num:num,type:0};
            }
        }
        this.updateTgSelect();
        this.checkBet();
    },

    //初始化
    init: function(lotteryId){
        this._lotteryID = lotteryId;
        this._isStops = -1;
        this._rules = DEFINE.LOTTERYRULEK3.TWODIFF;
    },

              //是否中奖后停止追号
    onIsStops:function(toggle, customEventData){
        if(toggle.isChecked == true)
        {
            this._isStops = 0;
        }
        else
        {
            this._isStops = -1;
        }
    },

    //选择清空切换
    onSelectCallBack:function(toggle){
        if(this._isNorm == 0)
        {
            toggle.getComponent(cc.Toggle).isChecked = true;
            this.clearAllBet();
        }
        else
        {
            if(toggle.getComponent(cc.Toggle).isChecked)
            {
                this.randomSelectCallBack();
            }
            else
            {
                this.clearAllBet();
            }
        }
    },

    //胆拖设置
    onChangeBallCallback:function(toggle){
       if(toggle.getComponent(cc.Toggle).isChecked)
       {
            this._isNorm = 0;
            ComponentsUtils.showTips("开始胆拖投注");
            this.labTip.string = "二不同号-胆拖投注";
       }
       else
       {
            this._isNorm = 1;
            this.labTip.string = "二不同号-标准投注";
       }
       this.updateTgSelect();
    },

    updateTgSelect:function(){
        if(this._redDiceNums.length>0 || this._yellowDiceNums.length>0)
        {
            this.tgSelect.getComponent(cc.Toggle).isChecked = true;
        }
        else
        {
            if(this._isNorm == 1)
            {
                this.tgSelect.getComponent(cc.Toggle).isChecked = false;
            }
            else
            {
                this.tgSelect.getComponent(cc.Toggle).isChecked = true;
            }
        } 
    },

    //随机选择
    randomSelectCallBack:function(){
        if(this._isNorm == 0 || this._yellowDiceNums.length>0)
            return false;
        this.clearAllBet();
        var randomRedArray = Utils.getRandomArrayWithArray(this.k3ToggleList, 2);
        for(var i=0;i<randomRedArray.length;i++)
        {
            randomRedArray[i].getComponent(cc.Toggle).isChecked = true;
            var temp = randomRedArray[i].checkEvents[0].customEventData;
            this.onClickCallBack(randomRedArray[i],temp);
        }   
        return true;
    },

      //计算
    checkBet:function(){
        var bet = 0;
        if(this._yellowDiceNums.length>0)
        {
            var len1 = this._redDiceNums.length;
            var len2 = this._yellowDiceNums.length;
            bet = len1 * len2;
            if(bet ==1 )//胆拖2注起投
                bet = 0;
        }
        else
        {
             var len1 = this._redDiceNums.length;
             var bet = LotteryUtils.combination(len1,2);
        }
        var muiple = this.getMutipleAmount();
        this.setShowAmount(muiple,bet);
    },

    //清除所有选择
    clearAllBet:function(){
        this._redDiceNums.length = 0;
        this._yellowDiceNums.length = 0;
        for(var i=0;i<this.k3ToggleList.length;i++)
        {
            this.k3ToggleList[i].checkEvents[0].customEventData = {num:i+1,type:0};
            this.k3ToggleList[i].getComponent(cc.Toggle).isChecked = false;
        }
        this._isNorm = 1;
        this.labTip.string = "二不同号-标准投注";
        this.k3ChangeTg.getComponent(cc.Toggle).isChecked = false;
        this.tgSelect.getComponent(cc.Toggle).isChecked = false;

        this._isStops = -1;
        this.tgIsStop.getComponent(cc.Toggle).isChecked = false;

        this.setIssueNum("1");
        this.setMutipleAmount("1");
        this.checkBet();
    },


    //设置金额
    setMoney:function(mon){
        this._curMoney = mon;
    },

    //得到金额
    getMoney:function(){
        return this._curMoney;
    },

    //设置注数
    setBetNum:function(num){
        this._curBetNum = num;
    },

    //得到注数
    getBetNum:function(){
        return this._curBetNum;
    },

    //设置期数
    setIssueNum:function(num){
        if(this._totalisuse >= parseInt(num))
        {
            this.edIssueNum.string = num;
        }
        else
        {
            ComponentsUtils.showTips("最大只能选择87期");
            this.edIssueNum.string = this._totalisuse.toString();
        }
        this.checkBet();
    },

    //得到期数
    getIssueNum:function(){
        var num = parseInt(this.edIssueNum.string);
        if(isNaN(num)){ 
            return 1;
        }else{
            return num;
        }        
    },

       //手动期数
    onEditBoxIssueChanged:function(editbox) {
        if(!Utils.isInt(editbox.string))
        {
            ComponentsUtils.showTips("输入格式错误！");
            editbox.string = "1";
        }
        if(editbox.string == null || editbox.string == "")
        {
            editbox.string = "1";
            ComponentsUtils.showTips("倍数不能为空！");
        }

        var amount = parseInt(editbox.string);
        if(isNaN(amount) || amount<=0 ){
            editbox.string = "1";
        }
  
       this.setIssueNum(editbox.string);
    },

    //设置倍数
    setMutipleAmount:function(mutiple){
         this.edMutipleNum.string = mutiple;
         this.checkBet();
    },

    //获取当前倍数
    getMutipleAmount:function(){
        var amount = parseInt(this.edMutipleNum.string);
        if(isNaN(amount)){ 
            return 1;
        }else{
            return amount;
        }        
    },

   //手动倍数
    onEditBoxMutipleChanged:function(editbox) {
        if(!Utils.isInt(editbox.string))
        {
            ComponentsUtils.showTips("输入格式错误！");
            editbox.string = "1";
        }
        if(editbox.string == null || editbox.string == "")
        {
            editbox.string = "1";
            ComponentsUtils.showTips("倍数不能为空！");
        }

        var amount = parseInt(editbox.string);
        if(isNaN(amount) || amount > 999 || amount<=0 ){
            editbox.string = "1";
        }
  
        this.checkBet();
    },

    //显示投注信息
    setShowAmount:function(mut,bet){
        var issue = this.getIssueNum();
        var money = mut*bet*this.BASEMONEY*issue;
        this.setMoney(money);
        this.setBetNum(bet);
        this.labSelectedAmount.string = "共"+bet+"注"+ mut +"倍"+ issue + "期"+ money+"元";
    },

    //投注信息组合
    dataToJson:function(){
        var objs = [];
        var obj1 = new Object(); 
        var arry1 = [];

        obj1.PlayCode = parseInt(this._lotteryID + this._rules); 
        var nums = "";
        var num = "";
        var isnr = this._yellowDiceNums.length>0?0:1;
        if(isnr == 1)
        {
            var dice = this._redDiceNums;
            Utils.sortNum(dice);
            num = "";
            for(var i = 0;i<dice.length;i++)
            {
                if(num != "")
                {
                    num+=",";
                }  
                num += dice[i].toString();
            }
            nums = num;
        }
        else
        {
            var dice1 =  this._yellowDiceNums;
            Utils.sortNum(dice1);
          
            num = "";
            for(var i = 0;i<dice1.length;i++)
            {
                if(num != "")
                {
                    num+=",";
                }  
                num += dice1[i].toString();
            }
            nums = num;

            var dice2 = this._redDiceNums;
             Utils.sortNum(dice2);
         
            num = "";
            for(var i = 0;i<dice2.length;i++)
            {
                if(num != "")
                {
                    num+=",";
                }  
                num += dice2[i].toString();
            }
            nums = nums+"#"+num;
        } 

        var numArrays = {
            "Multiple":this.getMutipleAmount(),
            "Bet":this.getBetNum(),
            "isNorm":isnr,
            "Number": nums//isnr == 0 ? encodeURIComponent(nums):nums
        };
        arry1.push(numArrays);

        obj1.Data = arry1.length >0 ? arry1 : null;
         
        if(obj1.Data != null )
        {
            JSON.stringify(obj1);
            objs.push(obj1);
        }

        var json = JSON.stringify(objs);
        cc.log("提交订单：" + json);
        return json;
    },

    //追号组合支付
    chasePay:function(){
        var recv = function(ret){
            ComponentsUtils.unblock(); 
            if(ret.Code === 0)
            {
                var len = ret.Data.length;
                if(len != this.getIssueNum())
                {
                    this.setIssueNum(len);
                    this.setShowAmount();
                }
                var obj = new Object(); 
                obj.Stops = this._isStops;
                obj.IsuseCount = len;
                obj.BeginTime = ret.Data[0].BeginTime;
                obj.EndTime = ret.Data[len-1].EndTime;
                var arry = [];
                for(var i=0;i<ret.Data.length;i++)
                {
                    var numArrays = {
                        "IsuseID":ret.Data[i].IsuseCode,
                        "Amount": LotteryUtils.moneytoClient(this.getMoney()/this.getIssueNum()),//每期金额
                        "Multiple":this.getMutipleAmount(),//每期总倍数
                    };
                    arry.push(numArrays);
                }
                obj.Data = arry;
                var json = JSON.stringify(obj);

                var data = {
                    lotteryId:this._lotteryID,//彩种id
                    dataBase:this.dataToJson(),//投注信息
                    otherBase:json,//追号
                    money:this.getMoney(), 
                    buyType: this.getIssueNum() >1?1:0,//追号
                }

                window.Notification.emit("BET_ONPAY",data);
            }
            else
            {
                ComponentsUtils.showTips(ret.Msg);
            }
        }.bind(this);
        var data = {
            Token:User.getLoginToken(),
            LotteryCode:this._lotteryID,
            Top:this.getIssueNum(),
        }
        CL.HTTP.sendRequest(DEFINE.HTTP_MESSAGE.GETADDTOISUSE, data, recv.bind(this),"POST");   
        ComponentsUtils.block();    
    },

   //关闭界面
    onClose:function(){
        window.Notification.emit("BET_ONCLOSE","");
    },

    //付款
    onPayBtn:function(){
        if(this.getMoney() <= 0)
            return;

        if(this.getIssueNum()<=1)
        {
            var data = {
                lotteryId:this._lotteryID,//彩种id
                dataBase:this.dataToJson(),//投注信息
                otherBase:"",//追加
                money:this.getMoney(),
                buyType: 0,//追号
            }
            window.Notification.emit("BET_ONPAY",data);
        }
        else
        {
            this.chasePay();
        }
    },

    onNextPage:function(){
        window.Notification.emit("BET_NEXTPAGE",1);
    },

    onLastPage:function(){
        window.Notification.emit("BET_NEXTPAGE",-1);
    },

    onMiss:function(toggle){
        if(toggle.getComponent(cc.Toggle).isChecked)
        {
            this._isMiss = true;
            this._betManage.showK3Miss(this.k3ToggleList,this._lotteryID,this._lotteryID + this._rules.toString(),false);
        }    
        else
        {
            this._isMiss = false;
            this._betManage.setK3Miss(false,this.k3ToggleList,"");
        }
    }

});
 